package com.cmcc.pcap.packet.util.pfcpUtile;

import com.cmcc.packet.entity.PfcpEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.util.HashMap;
import java.util.Map;

public class FSEIDUtil implements PfcpTypeUtil {
    private static Logger logger = LogManager.getLogger(UserPlaneIPResourceInformationUtil.class);
    boolean v4;
    boolean v6;
    int seid;
    Inet4Address ipv4;
    Inet6Address ipv6;

    @Override
    public PfcpEntity.InformationElement analysisIe(byte[] sub_payload) {
        PfcpEntity.InformationElement peie = new PfcpEntity.InformationElement();
        try {
            peie.setType(((sub_payload[0] & 0xff) << 8) + (sub_payload[1] & 0xff));
            peie.setLength(((sub_payload[2] & 0xff) << 8) + (sub_payload[3] & 0xff));
            Map<String, String> dataMap = new HashMap<>();
            int v6_flag = (sub_payload[4] << 1) & 0x1;
            dataMap.put("v6", String.valueOf(v6_flag));

            int v4_flag = (sub_payload[4] << 0) & 0x1;
            dataMap.put("v4", String.valueOf(v4_flag));

            byte[] seid_byte = new byte[8];
            System.arraycopy(sub_payload, 5, seid_byte, 0, 8);
            int seid = 0;
            for(int i=0;i<8;i++) {
                seid += (seid_byte[i] & 0xff) << (7-i)*8;
            }
            dataMap.put("seid", String.valueOf(seid));

            if(v4_flag==1){
                if(sub_payload.length >= 13+4*v4_flag) {
                    byte[] ipv4_byte = new byte[4];
                    System.arraycopy(sub_payload, 13, ipv4_byte, 0, 4);
                    dataMap.put("Ipv4Addres", String.valueOf(Inet4Address.getByAddress(ipv4_byte)));
                }else {
                    logger.error("Inadequate TLV length: %d", sub_payload.length);
                }
            }

            if(v6_flag==1) {
                if (sub_payload.length >= 13 + 4 * v4_flag + 16 * v6_flag) {
                    byte[] ipv6_byte = new byte[16];
                    System.arraycopy(sub_payload, 13 + 4 * v4_flag, ipv6_byte, 0, 16);
                    dataMap.put("Ipv6Addres", String.valueOf(Inet6Address.getByAddress(ipv6_byte)));
                } else {
                    logger.error("Inadequate TLV length: %d", sub_payload.length);
                }
            }
            peie.setDataMap(dataMap);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return peie;
    }

}
